package com.qf.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.qf.feigns.OrderServiceApi;
import com.qf.pojo.R;
import com.qf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

//@RestController
//@RequestMapping("/user")
//@RefreshScope //这个注解加上后，一旦配置信息发生变化，会重建该对象
public class UserController3 {

    @Value("${desc}")
    private String desc;

    @Autowired
    private OrderServiceApi orderServiceApi;

    @Autowired
    private UserService userService;

    @GetMapping("/{id}")
    @SentinelResource(value = "findOrders",/*fallback = "findOrdersFallback",blockHandler = "findOrdersBlockHandler",*/defaultFallback = "defaultFallback")
    public R findOrders(@PathVariable("id") Integer id) throws InterruptedException {

        System.out.println("===========desc:" + desc);

        R r = orderServiceApi.findByUid(id);

        return r;
    }

    //通过defaultFallback配置的降级方法，用来兜底处理，如果没有fallback和blockHandler配置时，他才生效
    //返回值和目标方法一致，参数列表留空，我们可以接收一个异常对象，处理异常，也可以不接收
    public R defaultFallback(Throwable t){
        t.printStackTrace();
        return R.error().putMsg("默认降级处理~~");
    }

    //通过blockHandler属性配置的降级方法，用来处理流控相关的异常。方法参数列表最后一个参数必须是BlockException e
    public R findOrdersBlockHandler(Integer id, BlockException e){
        e.printStackTrace();
        return R.error().putMsg("被流控了~~");
    }

    //通过fallback属性配置的降级方法，用来处理非流控相关的异常。方法参数列表中的Throwable t对象可有可无
    public R findOrdersFallback(Integer id,Throwable t){
        t.printStackTrace();
        return R.error().putMsg("服务器忙，稍后重试~~");
    }


    @GetMapping("/submit")
    @SentinelResource("submitOrder")
    public R submitOrder(){
        System.out.println("下单...");

        userService.getCarts();

        return R.success().putMsg("下单成功...");
    }

    @GetMapping("/carts")
    @SentinelResource("carts")
    public R carts(){
        userService.getCarts();
        return R.success().putMsg("查询购物车成功...");
    }


}
